<?php

namespace app\api\model;

use app\admin\model\GoodsCateModel;
use app\admin\model\VipCard;
use think\Model;
use think\model\concern\SoftDelete;

class GoodsModel extends ApiModel
{

    use SoftDelete;


    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [

    ];

    public function cate()
    {
        return $this->belongsTo(GoodsCateModel::class, 'goods_cate_id', 'id');
    }


    public function getGoodsList($params)
    {
        $uid =  $params['uid'] ?? 0;
        $vipDiscount = 0;

        $user = (new MemberModel())->where(['id' => $uid])->find();
        if($user && $user['vip_type'] > 0){
            $vipDiscount = (new VipCard())->where(['id' => $user['vip_type']])->value('discount');
        }
        $map = [];
        if (isset($params['cate_id']) && $params['cate_id']) {
            $map[] = ['goods_cate_id', '=', $params['cate_id']];
        }
        $list = self::where(['status' => 1])
            ->field('id,title,image,price,stock,residue_stock,sales,content')
            ->order('sort desc,id asc')
            ->where($map)
            ->paginate(10);

        if ($list->items()) {
            foreach ($list as $key => &$val) {
                $val['image'] = config('app.image_url') . $val['image'];
                $val['content'] = $this->get_img_thumb_url($val['content'], config('app.image_url'));
                $val['sales'] = $this->formatSoldCount($val['sales']);
                $val['vip_price'] = '';
                if($vipDiscount){
                    $val['vip_price'] = number_format($val['price'] * $vipDiscount / 10,2) . "";
                }
            }

        }
        return $this->api_success('获取成功', $list);
    }


    public function get_img_thumb_url($content = "", $suffix ='')
    {
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img src="' . $suffix . '${1}" style="max-width:100%">', $content);
        return $content;
    }

    public function formatSoldCount($nums)
    {
        if ($nums < 1000) {
            return "已售{$nums}件";
        } elseif ($nums >= 1000 && $nums < 10000) {
            return "已售" . round($nums / 1000, 1) . "K+件";
        } elseif ($nums >= 10000 && $nums < 100000) {
            return "已售" . round($nums / 10000, 1) . "W+件";
        } elseif ($nums >= 100000) {
            return "已售" . round($nums / 100000, 1) . "10W+件";
        }
    }


}
